package com.yhtx.easy.exception;

import com.yhtx.easy.result.ErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

@RestControllerAdvice
public class GlobalExceptionHandler {


    // 拦截抛出的异常，@ResponseStatus：用来改变响应状态码
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Throwable.class)
    public ErrorResponse handlerThrowable(Throwable e, HttpServletRequest request) {
        //默认用500
        Integer code = null;
        try {
            Field codeField = e.getClass().getDeclaredField("code");
            codeField.setAccessible(true);
            code =  (Integer) codeField.get(e);
        } catch (Exception exc) {
            code = ExceptionEnum.SYSTEM_ERROR.getCode();
        }
        return new ErrorResponse(code.toString(),e.getMessage());
    }

    // 参数校验异常
    @ExceptionHandler(BindException.class)
    public ErrorResponse handleBindException(BindException e, HttpServletRequest request) {
        return new ErrorResponse(ExceptionEnum.PARAM_IS_INVALID.getCode().toString(),ExceptionEnum.PARAM_IS_INVALID.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ErrorResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        return new ErrorResponse(ExceptionEnum.PARAM_IS_INVALID.getCode().toString(),e.getFieldError().getDefaultMessage());
    }
}
